<?php

use Illuminate\Support\Facades\Route;
use App\Http\Controllers\Api\AuthController;
use App\Http\Controllers\Api\RoomController;
use App\Http\Controllers\Api\OrderController;
use App\Http\Controllers\Api\MenuController;
use App\Http\Controllers\Api\CategoryController;

/*
|--------------------------------------------------------------------------
| Web Routes
|--------------------------------------------------------------------------
|
| 简化版Web管理系统路由
| 复用API控制器，使用User表进行认证
|
*/

// 首页重定向到管理后台
Route::get('/', function () {
    return redirect('/admin');
});

// 管理后台路由组
Route::prefix('admin')->name('admin.')->group(function () {
    
    // 登录页面（不需要认证）
    Route::get('login', function () {
        return view('admin.login');
    })->name('login');
    
    
    // 处理登录
    Route::post('login', [AuthController::class, 'webLogin'])->name('login.post');
    
    // 登出
    Route::post('logout', [AuthController::class, 'logout'])->name('logout');
    
    // 需要认证的管理后台页面
    Route::middleware(['auth:web', 'log.admin'])->group(function () {
        
        // 仪表板
        Route::get('/', [\App\Http\Controllers\Admin\DashboardController::class, 'index'])->name('dashboard');
        
        // 用户管理
        Route::get('/users', [\App\Http\Controllers\Admin\UserController::class, 'index'])->name('users.index');
        Route::get('/users/{id}', [\App\Http\Controllers\Admin\UserController::class, 'show'])->name('users.show');
        Route::post('/users/{id}/toggle-status', [\App\Http\Controllers\Admin\UserController::class, 'toggleStatus'])->name('users.toggle-status');
        
        // 房间管理
        Route::get('/rooms', [\App\Http\Controllers\Admin\RoomController::class, 'index'])->name('rooms.index');
        Route::get('/rooms/create', [\App\Http\Controllers\Admin\RoomController::class, 'create'])->name('rooms.create');
        Route::post('/rooms', [\App\Http\Controllers\Admin\RoomController::class, 'store'])->name('rooms.store');
        Route::get('/rooms/{id}', [\App\Http\Controllers\Admin\RoomController::class, 'show'])->name('rooms.show');
        Route::get('/rooms/{id}/edit', [\App\Http\Controllers\Admin\RoomController::class, 'edit'])->name('rooms.edit');
        Route::put('/rooms/{id}', [\App\Http\Controllers\Admin\RoomController::class, 'update'])->name('rooms.update');
        Route::delete('/rooms/{id}', [\App\Http\Controllers\Admin\RoomController::class, 'destroy'])->name('rooms.destroy');
        Route::post('/rooms/{id}/toggle-status', [\App\Http\Controllers\Admin\RoomController::class, 'toggleStatus'])->name('rooms.toggle-status');
        
        // 菜品管理
        Route::get('/dishes', [\App\Http\Controllers\Admin\DishController::class, 'index'])->name('dishes.index');
        Route::get('/dishes/create', [\App\Http\Controllers\Admin\DishController::class, 'create'])->name('dishes.create');
        Route::post('/dishes', [\App\Http\Controllers\Admin\DishController::class, 'store'])->name('dishes.store');
        Route::get('/dishes/{id}', [\App\Http\Controllers\Admin\DishController::class, 'show'])->name('dishes.show');
        Route::get('/dishes/{id}/edit', [\App\Http\Controllers\Admin\DishController::class, 'edit'])->name('dishes.edit');
        Route::put('/dishes/{id}', [\App\Http\Controllers\Admin\DishController::class, 'update'])->name('dishes.update');
        Route::delete('/dishes/{id}', [\App\Http\Controllers\Admin\DishController::class, 'destroy'])->name('dishes.destroy');
        Route::post('/dishes/{id}/toggle-featured', [\App\Http\Controllers\Admin\DishController::class, 'toggleFeatured'])->name('dishes.toggle-featured');
        
        // 订单管理
        Route::get('/orders', [\App\Http\Controllers\Admin\OrderController::class, 'index'])->name('orders.index');
        Route::get('/orders/{id}', [\App\Http\Controllers\Admin\OrderController::class, 'show'])->name('orders.show');
        Route::post('/orders/{id}/confirm', [\App\Http\Controllers\Admin\OrderController::class, 'confirm'])->name('orders.confirm');
        Route::post('/orders/{id}/cancel', [\App\Http\Controllers\Admin\OrderController::class, 'cancel'])->name('orders.cancel');
        Route::patch('/orders/{id}/status', [\App\Http\Controllers\Admin\OrderController::class, 'updateStatus'])->name('orders.update-status');
        
        // 分类管理
        Route::get('/categories', [\App\Http\Controllers\Admin\CategoryController::class, 'index'])->name('categories.index');
        Route::get('/categories/create', [\App\Http\Controllers\Admin\CategoryController::class, 'create'])->name('categories.create');
        Route::post('/categories', [\App\Http\Controllers\Admin\CategoryController::class, 'store'])->name('categories.store');
        Route::get('/categories/{id}', [\App\Http\Controllers\Admin\CategoryController::class, 'show'])->name('categories.show');
        Route::get('/categories/{id}/edit', [\App\Http\Controllers\Admin\CategoryController::class, 'edit'])->name('categories.edit');
        Route::put('/categories/{id}', [\App\Http\Controllers\Admin\CategoryController::class, 'update'])->name('categories.update');
        Route::delete('/categories/{id}', [\App\Http\Controllers\Admin\CategoryController::class, 'destroy'])->name('categories.destroy');
        Route::post('/categories/{id}/toggle-status', [\App\Http\Controllers\Admin\CategoryController::class, 'toggleStatus'])->name('categories.toggle-status');

        // 菜单管理
        Route::get('/menus', [\App\Http\Controllers\Admin\MenuController::class, 'index'])->name('menus.index');
        Route::get('/menus/create', [\App\Http\Controllers\Admin\MenuController::class, 'create'])->name('menus.create');
        Route::post('/menus', [\App\Http\Controllers\Admin\MenuController::class, 'store'])->name('menus.store');
        Route::get('/menus/{menu}', [\App\Http\Controllers\Admin\MenuController::class, 'show'])->name('menus.show');
        Route::get('/menus/{menu}/edit', [\App\Http\Controllers\Admin\MenuController::class, 'edit'])->name('menus.edit');
        Route::put('/menus/{menu}', [\App\Http\Controllers\Admin\MenuController::class, 'update'])->name('menus.update');
        Route::delete('/menus/{menu}', [\App\Http\Controllers\Admin\MenuController::class, 'destroy'])->name('menus.destroy');
        Route::post('/menus/{menu}/toggle-public', [\App\Http\Controllers\Admin\MenuController::class, 'togglePublic'])->name('menus.toggle-public');
        Route::post('/menus/{menu}/toggle-template', [\App\Http\Controllers\Admin\MenuController::class, 'toggleTemplate'])->name('menus.toggle-template');
        Route::post('/menus/{menu}/add-dish', [\App\Http\Controllers\Admin\MenuController::class, 'addDish'])->name('menus.add-dish');

        // 日志管理
        Route::get('/logs', [\App\Http\Controllers\Admin\LogController::class, 'index'])->name('logs.index');
        Route::get('/logs/{id}', [\App\Http\Controllers\Admin\LogController::class, 'show'])->name('logs.show');
        Route::delete('/logs/{id}', [\App\Http\Controllers\Admin\LogController::class, 'destroy'])->name('logs.destroy');
        Route::post('/logs/batch-destroy', [\App\Http\Controllers\Admin\LogController::class, 'batchDestroy'])->name('logs.batch-destroy');
        Route::post('/logs/clean', [\App\Http\Controllers\Admin\LogController::class, 'cleanOldLogs'])->name('logs.clean');
        Route::get('/logs/export', [\App\Http\Controllers\Admin\LogController::class, 'export'])->name('logs.export');
        Route::get('/logs/chart-data', [\App\Http\Controllers\Admin\LogController::class, 'getChartData'])->name('logs.chart-data');
        
    });
});

// API数据接口（复用现有API）
Route::prefix('admin/api')->middleware('auth:web')->group(function () {
    
    // 仪表板数据
    Route::get('/stats', function () {
        $stats = [
            'users' => \App\Models\User::count(),
            'rooms' => \App\Models\Room::count(),
            'dishes' => \App\Models\Dish::count(),
            'orders' => \App\Models\Order::count(),
            'active_rooms' => \App\Models\Room::where('status', 'active')->count(),
            'today_orders' => \App\Models\Order::whereDate('created_at', today())->count(),
        ];
        return response()->json($stats);
    })->name('api.stats');
    
    // 用户数据
    Route::get('/users', [\App\Http\Controllers\Admin\UserController::class, 'list'])->name('api.users');
    Route::get('/users/{id}', [\App\Http\Controllers\Admin\UserController::class, 'showApi'])->name('api.user-show');
    Route::get('/users/stats', [\App\Http\Controllers\Admin\UserController::class, 'stats'])->name('api.user-stats');
    
    // 房间数据
    Route::get('/rooms', [\App\Http\Controllers\Admin\RoomController::class, 'list'])->name('api.rooms');
    Route::get('/rooms/{id}', [\App\Http\Controllers\Admin\RoomController::class, 'showApi'])->name('api.room-show');
    Route::get('/rooms/stats', [\App\Http\Controllers\Admin\RoomController::class, 'stats'])->name('api.room-stats');
    
    // 菜品数据
    Route::get('/dishes', function () {
        $dishes = \App\Models\Dish::with('category')
            ->orderBy('created_at', 'desc')
            ->paginate(20);
        
        $dishesData = $dishes->map(function($dish) {
            return [
                'id' => $dish->id,
                'name' => $dish->name,
                'description' => $dish->description,
                'category_id' => $dish->category_id,
                'category' => $dish->category ? [
                    'id' => $dish->category->id,
                    'name' => $dish->category->name,
                    'slug' => $dish->category->slug
                ] : null,
                'tags' => $dish->tags,
                'flavors' => $dish->flavors,
                'cooking_time' => $dish->cooking_time,
                'sort_order' => $dish->sort_order,
                'is_featured' => $dish->is_featured,
                'view_count' => $dish->view_count,
                'order_count' => $dish->order_count,
                'favorite_count' => $dish->favorite_count,
                'created_at' => $dish->created_at->format('Y-m-d H:i:s'),
                'updated_at' => $dish->updated_at->format('Y-m-d H:i:s')
            ];
        });
        
        return response()->json([
            'data' => $dishesData,
            'pagination' => [
                'current_page' => $dishes->currentPage(),
                'last_page' => $dishes->lastPage(),
                'per_page' => $dishes->perPage(),
                'total' => $dishes->total()
            ]
        ]);
    })->name('api.dishes');
    
    // 订单数据
    Route::get('/orders', [\App\Http\Controllers\Admin\OrderController::class, 'list'])->name('api.orders');
    Route::get('/orders/{id}', [\App\Http\Controllers\Admin\OrderController::class, 'showApi'])->name('api.order-show');
    Route::get('/orders/stats', [\App\Http\Controllers\Admin\OrderController::class, 'stats'])->name('api.order-stats');
    
    // 分类数据
    Route::get('/categories', function () {
        $categories = \App\Models\Category::withCount('dishes')
            ->orderBy('sort_order')
            ->get();
        return response()->json($categories);
    })->name('api.categories');
    
    // 最近活动数据
    Route::get('/activities', function () {
        $activities = [];
        
        // 最近注册的用户
        $recentUsers = \App\Models\User::orderBy('created_at', 'desc')->limit(3)->get();
        foreach ($recentUsers as $user) {
            $activities[] = [
                'id' => 'user_' . $user->id,
                'description' => '新用户 ' . ($user->nickname ?? '用户' . $user->id) . ' 注册了账号',
                'time' => $user->created_at->diffForHumans(),
                'type' => 'user_registered'
            ];
        }
        
        // 最近创建的房间
        $recentRooms = \App\Models\Room::orderBy('created_at', 'desc')->limit(3)->get();
        foreach ($recentRooms as $room) {
            $activities[] = [
                'id' => 'room_' . $room->id,
                'description' => '房间 "' . $room->name . '" 创建成功',
                'time' => $room->created_at->diffForHumans(),
                'type' => 'room_created'
            ];
        }
        
        // 最近完成的订单
        $recentOrders = \App\Models\Order::orderBy('created_at', 'desc')->limit(3)->get();
        foreach ($recentOrders as $order) {
            $activities[] = [
                'id' => 'order_' . $order->id,
                'description' => '订单 #' . $order->id . ' 已完成',
                'time' => $order->created_at->diffForHumans(),
                'type' => 'order_completed'
            ];
        }
        
        // 按时间排序
        usort($activities, function($a, $b) {
            return strtotime($b['time']) - strtotime($a['time']);
        });
        
        return response()->json(array_slice($activities, 0, 5));
    })->name('api.activities');
    
    // 最近订单数据
    Route::get('/recent-orders', function () {
        $orders = \App\Models\Order::with(['user', 'room'])
            ->orderBy('created_at', 'desc')
            ->limit(5)
            ->get()
            ->map(function($order) {
                // 获取订单菜品信息
                $dishes = $order->dishes ?? [];
                $dishCount = count($dishes);
                $totalQuantity = array_sum(array_column($dishes, 'quantity'));
                
                return [
                    'id' => $order->id,
                    'number' => '#' . $order->order_id,
                    'user' => $order->user->nickname ?? '用户' . $order->user_id,
                    'dish_count' => $dishCount,
                    'total_quantity' => $totalQuantity,
                    'status' => $order->status === 'confirmed' ? '已完成' : ($order->status === 'cancelled' ? '已取消' : '处理中'),
                    'created_at' => $order->created_at->format('Y-m-d H:i')
                ];
            });
        
        return response()->json($orders);
    })->name('api.recent-orders');
    
    // 用户详情
    Route::get('/users/{id}', function ($id) {
        $user = \App\Models\User::with(['createdRooms', 'joinedRooms', 'orders'])
            ->findOrFail($id);
        
        $totalRooms = $user->createdRooms->count() + $user->joinedRooms->count();
        
        return response()->json([
            'id' => $user->id,
            'openid' => $user->openid,
            'nickname' => $user->nickname,
            'avatar' => $user->avatar,
            'phone' => $user->phone,
            'gender' => $user->gender,
            'city' => $user->city,
            'province' => $user->province,
            'country' => $user->country,
            'language' => $user->language,
            'is_active' => $user->is_active,
            'rooms_count' => $totalRooms,
            'orders_count' => $user->orders->count(),
            'created_at' => $user->created_at->format('Y-m-d H:i:s'),
            'updated_at' => $user->updated_at->format('Y-m-d H:i:s'),
            'created_rooms' => $user->createdRooms->map(function($room) {
                return [
                    'id' => $room->id,
                    'name' => $room->name,
                    'status' => $room->status,
                    'created_at' => $room->created_at->format('Y-m-d H:i:s')
                ];
            }),
            'joined_rooms' => $user->joinedRooms->map(function($room) {
                return [
                    'id' => $room->id,
                    'name' => $room->name,
                    'status' => $room->status,
                    'joined_at' => $room->pivot->joined_at
                ];
            }),
            'recent_orders' => $user->orders()->with('room')->orderBy('created_at', 'desc')->limit(10)->get()->map(function($order) {
                $dishes = $order->dishes ?? [];
                $dishCount = count($dishes);
                $totalQuantity = array_sum(array_column($dishes, 'quantity'));
                
                return [
                    'id' => $order->id,
                    'order_id' => $order->order_id,
                    'room' => $order->room ? [
                        'id' => $order->room->id,
                        'name' => $order->room->name
                    ] : null,
                    'dishes_count' => $dishCount,
                    'total_quantity' => $totalQuantity,
                    'status' => $order->status,
                    'created_at' => $order->created_at->format('Y-m-d H:i:s')
                ];
            })
        ]);
    })->name('api.user-detail');
    
    // 订单详情
    Route::get('/orders/{id}', function ($id) {
        $order = \App\Models\Order::with(['user', 'room'])
            ->findOrFail($id);
        
        $dishes = $order->dishes ?? [];
        $dishCount = count($dishes);
        $totalQuantity = array_sum(array_column($dishes, 'quantity'));
        
        return response()->json([
            'id' => $order->id,
            'order_id' => $order->order_id,
            'user' => $order->user ? [
                'id' => $order->user->id,
                'nickname' => $order->user->nickname,
                'phone' => $order->user->phone,
                'avatar' => $order->user->avatar
            ] : null,
            'room' => $order->room ? [
                'id' => $order->room->id,
                'name' => $order->room->name,
                'status' => $order->room->status
            ] : null,
            'dishes' => $dishes,
            'dishes_count' => $dishCount,
            'total_quantity' => $totalQuantity,
            'status' => $order->status,
            'payment_status' => $order->payment_status,
            'payment_method' => $order->payment_method,
            'payment_time' => $order->payment_time,
            'notes' => $order->notes,
            'created_at' => $order->created_at->format('Y-m-d H:i:s'),
            'updated_at' => $order->updated_at->format('Y-m-d H:i:s')
        ]);
    })->name('api.order-detail');
    
    // 用户状态切换
    Route::post('/users/{id}/toggle-status', function ($id) {
        $user = \App\Models\User::findOrFail($id);
        $user->is_active = !$user->is_active;
        $user->save();
        
        return response()->json([
            'success' => true,
            'is_active' => $user->is_active
        ]);
    })->name('api.user-toggle-status');
    
    // 订单确认
    Route::post('/orders/{id}/confirm', function ($id) {
        $order = \App\Models\Order::findOrFail($id);
        $order->status = 'confirmed';
        $order->save();
        
        return response()->json([
            'success' => true,
            'status' => $order->status
        ]);
    })->name('api.order-confirm');
    
    // 订单取消
    Route::post('/orders/{id}/cancel', function ($id) {
        $order = \App\Models\Order::findOrFail($id);
        $order->status = 'cancelled';
        $order->save();
        
        return response()->json([
            'success' => true,
            'status' => $order->status
        ]);
    })->name('api.order-cancel');
    
    // 分类CRUD操作
    Route::get('/categories', [\App\Http\Controllers\Admin\CategoryController::class, 'list'])->name('api.categories');
    Route::get('/categories/all', [\App\Http\Controllers\Admin\CategoryController::class, 'all'])->name('api.categories-all');
    Route::get('/categories/{id}', [\App\Http\Controllers\Admin\CategoryController::class, 'show'])->name('api.category-show');
    Route::post('/categories', [\App\Http\Controllers\Admin\CategoryController::class, 'store'])->name('api.category-create');
    Route::put('/categories/{id}', [\App\Http\Controllers\Admin\CategoryController::class, 'update'])->name('api.category-update');
    Route::delete('/categories/{id}', [\App\Http\Controllers\Admin\CategoryController::class, 'destroy'])->name('api.category-delete');
    Route::post('/categories/{id}/toggle-status', [\App\Http\Controllers\Admin\CategoryController::class, 'toggleStatus'])->name('api.category-toggle-status');
    Route::get('/categories/stats', [\App\Http\Controllers\Admin\CategoryController::class, 'stats'])->name('api.category-stats');
    
    // 菜品CRUD操作
    Route::get('/dishes', [\App\Http\Controllers\Admin\DishController::class, 'list'])->name('api.dishes');
    Route::get('/dishes/{id}', [\App\Http\Controllers\Admin\DishController::class, 'show'])->name('api.dish-show');
    Route::post('/dishes', [\App\Http\Controllers\Admin\DishController::class, 'store'])->name('api.dish-create');
    Route::put('/dishes/{id}', [\App\Http\Controllers\Admin\DishController::class, 'update'])->name('api.dish-update');
    Route::delete('/dishes/{id}', [\App\Http\Controllers\Admin\DishController::class, 'destroy'])->name('api.dish-delete');
    Route::post('/dishes/{id}/toggle-featured', [\App\Http\Controllers\Admin\DishController::class, 'toggleFeatured'])->name('api.dish-toggle-featured');
    Route::get('/dishes/category/{categoryId}', [\App\Http\Controllers\Admin\DishController::class, 'byCategory'])->name('api.dishes-by-category');
    Route::get('/dishes/featured', [\App\Http\Controllers\Admin\DishController::class, 'featured'])->name('api.dishes-featured');
    Route::get('/dishes/search', [\App\Http\Controllers\Admin\DishController::class, 'search'])->name('api.dishes-search');
    Route::get('/dishes/stats', [\App\Http\Controllers\Admin\DishController::class, 'stats'])->name('api.dish-stats');
    Route::post('/dishes/batch-update-category', [\App\Http\Controllers\Admin\DishController::class, 'batchUpdateCategory'])->name('api.dishes-batch-update-category');
    Route::post('/dishes/batch-set-featured', [\App\Http\Controllers\Admin\DishController::class, 'batchSetFeatured'])->name('api.dishes-batch-set-featured');
});